package com.ruoyi.web.controller.system;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.system.domain.UpdateStatusRequest;
import com.ruoyi.system.mapper.TMiStockMapper;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.TMiStock;
import com.ruoyi.system.service.ITMiStockService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 库存Controller
 *
 * @author ruoyi
 * @date 2024-09-04
 */
@RestController
@RequestMapping("/system/STOCK")
public class TMiStockController extends BaseController
{
    @Autowired
    private ITMiStockService tMiStockService;
    @Autowired
    private TMiStockMapper tMiStockMapper;

    /**
     * 查询【请填写功能名称】列表
     */
    @PreAuthorize("@ss.hasPermi('system:STOCK:list')")
    @GetMapping("/list")
    public TableDataInfo list(TMiStock tMiStock)
    {
        String[] addTimes = tMiStock.getWareDates();
        if (addTimes != null && addTimes.length > 1) {
            tMiStock.setStartTime(addTimes[0]);
            tMiStock.setEndsTime(addTimes[1]);
        }
        startPage();
        List<TMiStock> list = tMiStockService.selectTMiStockList(tMiStock);
        // 对 list 进行排序，使得库位字段按照主要部分和尾数的顺序交替展示
        list.sort((a, b) -> {
            String locationA = a.getLocationId();
            String locationB = b.getLocationId();

            // 提取库位的主要部分和尾数
            String mainPartA = locationA.substring(0, locationA.lastIndexOf('-'));
            String mainPartB = locationB.substring(0, locationB.lastIndexOf('-'));
            String suffixA = locationA.substring(locationA.lastIndexOf('-') + 1);
            String suffixB = locationB.substring(locationB.lastIndexOf('-') + 1);

            // 先按主要部分排序
            int mainPartComparison = mainPartA.compareTo(mainPartB);
            if (mainPartComparison != 0) {
                return mainPartComparison;
            }

            // 如果主要部分相同，按尾数排序
            return Integer.compare(Integer.parseInt(suffixA), Integer.parseInt(suffixB));
        });

        // 交替排列
        List<TMiStock> result = new ArrayList<>();
        Map<String, List<TMiStock>> grouped = list.stream()
                .collect(Collectors.groupingBy(stock -> stock.getLocationId().substring(0, stock.getLocationId().lastIndexOf('-'))));

        // 交替添加到结果列表
        while (grouped.values().stream().anyMatch(group -> !group.isEmpty())) {
            for (List<TMiStock> group : grouped.values()) {
                if (!group.isEmpty()) {
                    result.add(group.remove(0)); // 从每个组中取出一个元素
                }
            }
        }
        return getDataTable(list);
    }

    /*@PreAuthorize("@ss.hasPermi('system:STOCK:lists')")*/
    @GetMapping("/lists")
    public AjaxResult lists(TMiStock tMiStock)
    {
        String[] addTimes = tMiStock.getWareDates();
        if (addTimes != null && addTimes.length > 1) {
            tMiStock.setStartTime(addTimes[0]);
            tMiStock.setEndsTime(addTimes[1]);
        }
        List<TMiStock> list = tMiStockService.selectTMiStockList(tMiStock);
        // 对 list 进行排序，使得库位字段按照 -1 和 -2 的顺序交替展示
        list.sort((a, b) -> {
            String locationA = a.getLocationId();
            String locationB = b.getLocationId();

            // 检查locationA和locationB是否包含'-'
            int indexA = locationA.lastIndexOf('-');
            int indexB = locationB.lastIndexOf('-');

            if (indexA == -1 || indexB == -1) {
                // 如果任一locationId不包含'-'，则直接比较整个字符串
                // 或者，您也可以选择抛出一个异常或进行其他错误处理
                return locationA.compareTo(locationB);
            }

            // 提取库位的主要部分和尾数
            String mainPartA = locationA.substring(0, indexA);
            String mainPartB = locationB.substring(0, indexB);
            String suffixA = locationA.substring(indexA + 1);
            String suffixB = locationB.substring(indexB + 1);

            // 先按主要部分排序
            int mainPartComparison = mainPartA.compareTo(mainPartB);
            if (mainPartComparison != 0) {
                return mainPartComparison;
            }

            // 如果主要部分相同，按尾数排序
            return suffixA.compareTo(suffixB);
        });
        return success(list);
    }

    /**
     * 导出【请填写功能名称】列表
     */
    @PreAuthorize("@ss.hasPermi('system:STOCK:export')")
    @Log(title = "导出库存数据", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TMiStock tMiStock)
    {
        List<TMiStock> list = tMiStockService.selectTMiStockList(tMiStock);
        ExcelUtil<TMiStock> util = new ExcelUtil<TMiStock>(TMiStock.class);
        util.exportExcel(response, list, "库存报表");
    }

    /**
     * 获取【请填写功能名称】详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:STOCK:query')")
    @GetMapping(value = "/{stockId}")
    public AjaxResult getInfo(@PathVariable("stockId") String stockId)
    {
        return success(tMiStockService.selectTMiStockByStockId(stockId));
    }

    /**
     * 新增【请填写功能名称】
     */
    @PreAuthorize("@ss.hasPermi('system:STOCK:add')")
    @Log(title = "新增库存", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TMiStock tMiStock)
    {
        return toAjax(tMiStockService.insertTMiStock(tMiStock));
    }

    /**
     * 修改【请填写功能名称】
     */
    @PreAuthorize("@ss.hasPermi('system:STOCK:edit')")
    @Log(title = "修改库存", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TMiStock tMiStock)
    {
        return toAjax(tMiStockService.updateTMiStock(tMiStock));
    }
    @Log(title = "解冻", businessType = BusinessType.UPDATE)
    @PostMapping("/update")
    public AjaxResult update(@RequestBody TMiStock tMiStock){

        return toAjax(tMiStockMapper.updatests(tMiStock));
    }


    /**
     * 删除【请填写功能名称】
     */
    @PreAuthorize("@ss.hasPermi('system:STOCK:remove')")
    @Log(title = "删除库存", businessType = BusinessType.DELETE)
    @DeleteMapping("/{stockIds}")
    public AjaxResult remove(@PathVariable String[] stockIds)
    {
        return toAjax(tMiStockService.deleteTMiStockByStockIds(stockIds));
    }
    @Log(title = "根据库位查询库存", businessType = BusinessType.SELECT)
    @GetMapping(value = "/list/{locationId}")
    public TableDataInfo getInfoList(@PathVariable("locationId") String locationId) {
        startPage();
        List<TMiStock> stocks = tMiStockService.selectTMiStocksByLocationId(locationId);
        return getDataTable(stocks);
    }

    @PostMapping("/sts")
    public AjaxResult updateStatus(@RequestBody UpdateStatusRequest request) {

        return toAjax(tMiStockService.updateStatus(request));
    }
}
